<?php
/**
 * User: Kris
 * Date: 1/10/12
 * Time: 4:38 PM
 */

require_once APPPATH . 'core/controller.php';

class Frontpage extends Controller
{
    public function index()
    {
        $this->data['styles'][] = "/public/css/frontpage-index.css";

        if ($this->session->userdata('loggedin') == true)
        {
            //Loading userspecific page
            $this->loadPersonalPage();
            $this->parser->parse("Frontpage/index-personalized.tpl", $this->data);
        }
        else
        {
            //Loading default page
            $this->loadDefault();
            $this->parser->parse("Frontpage/index.tpl", $this->data);
        }

    }

    private function loadPersonalPage() {
        $user = $this->em->find('User', $this->session->userdata('userId'));
        $categorySubscriptions = $user->getCategorySubscriptions();
        $channelSubscriptions = $user->getChannelSubscriptions();

        $perCategoryPosts = array();
        $perChannelPosts = array();

        $topThree = new TopThreePosts();

        foreach($categorySubscriptions as $category) {
            //Selected category's latest posts
            $currentCategoryLatestPosts = $this->em->createQuery("SELECT p FROM Post p JOIN p.category c WHERE c.id = :categoryId ORDER BY p.id DESC")->setMaxResults(5);
            $currentCategoryLatestPosts->setParameter('categoryId', $category->getId());

            $perCategoryPosts[$category->getName()] = $currentCategoryLatestPosts->getResult();

        }

        foreach ($channelSubscriptions as $channel) {
            $currentChannelLatestPosts = $this->em->createQuery("SELECT p FROM Post p Join p.channels c WHERE c.id = :channelId ORDER BY p.id DESC")->setMaxResults(5);
            $currentChannelLatestPosts->setParameter('channelId', $channel->getId());
            $perChannelPosts[$channel->getName()] = $currentChannelLatestPosts->getResult();
        }

        $contentBlocks = array_merge($perCategoryPosts, $perChannelPosts);

        foreach ($contentBlocks as $blockName => $contentBlock) {
            foreach ($contentBlock as $post) {
                $topThree->validateAndAdd($post);
            }
        }

        $this->data['topThree'] = $topThree->getTopThree();
        $this->data['categoryBlocksContent'] = $perCategoryPosts;
        $this->data['channelBlocksContent'] = $perChannelPosts;
    }

    private function loadDefault() {

        $topThree = new TopThreePosts();

        $posts = $this->em->createQuery("SELECT p FROM Post p ORDER BY p.id DESC")->setMaxResults(21);
        $featuredPosts = $posts->getResult();


        foreach ($featuredPosts as $post) {
            $topThree->validateAndAdd($post);
        }

        $this->data['featuredPosts'] = $featuredPosts;
        $this->data['topThree'] = $topThree->getTopThree();

    }

    public function testModel()
    {
        $this->posts->getLastPostByCategoryName(1, 'Test');

    }

    public function insert()
    {
        $posts = $this->generateTestPosts();
        $this->insertTestPosts($posts);
    }

    /**
     * @return array
     */
    private function generateTestPosts()
    {
        $posts = array();

        for ($i = 1; $i < 4; $i++)
        {
            $user = $this->em->find('User', $i);
            $post = new Post();
            $post->setAuthor($user);
            $post->setTitle("Titel");

            $category = $this->em->find('Category', ($i % 2 + 1));
            $post->setCategory($category);

            $content = new Post_Content();
            $content->setContent("<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ornare tincidunt facilisis. Donec sodales accumsan felis, aliquet elementum justo tempus sit amet. Integer sit amet nibh et lectus vestibulum mollis. Fusce quis diam vitae sapien viverra suscipit. Cras eu justo orci, vel imperdiet tellus. Nam lobortis nunc a odio viverra ornare. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Proin luctus dui vitae tellus tempus aliquet quis in turpis.</p>

                        <p>Nam molestie, augue vel lacinia interdum, lorem nisl mollis dolor, ac venenatis neque risus nec ligula. Vivamus vulputate hendrerit ultricies. Ut at hendrerit tellus. Nulla nisi lectus, consequat lacinia auctor et, dignissim sed mi. Etiam viverra fermentum mollis. In consequat ante fermentum eros malesuada vitae molestie augue cursus. Sed vehicula lacus vitae arcu dignissim convallis. Sed leo elit, consequat sed auctor et, viverra eu est.</p>

                        <p>Pellentesque odio tortor, aliquet vitae hendrerit sit amet, interdum sit amet sem. Vivamus pellentesque nisi in diam varius vel vestibulum ante gravida. Ut rutrum pretium arcu, a congue purus feugiat in. Sed hendrerit lectus eget neque vestibulum dignissim. In facilisis diam vitae neque molestie accumsan. Pellentesque rhoncus nibh id lorem posuere id venenatis quam laoreet. Sed nec justo nec lacus semper imperdiet vitae sed tellus. Nunc pulvinar, magna a gravida auctor, nulla felis volutpat felis, sed luctus augue leo nec est. Praesent auctor, leo vel viverra blandit, nibh sem mollis purus, eget gravida nibh dolor a lacus. Fusce mi enim, congue at feugiat eu, mattis et nisl. Donec ut nisi odio, eu tristique lorem. Integer semper metus nec urna blandit convallis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Duis eros nisl, condimentum nec tincidunt vel, dapibus et lacus. Suspendisse mattis eros feugiat lectus ultricies a convallis neque porttitor.</p>

                        <p>Praesent cursus justo at turpis congue accumsan. Donec erat eros, mollis sit amet auctor non, elementum nec diam. Curabitur dapibus nibh sed augue tempus eleifend. Sed eros dui, eleifend a consectetur in, suscipit sit amet dui. Curabitur urna erat, tempor et gravida ut, gravida ac justo. Cras vel varius dolor. Phasellus justo lectus, blandit placerat elementum quis, tincidunt ac risus. Vivamus ut felis diam, ut dapibus est. Morbi nec massa velit.</p>

                        <p>In nibh sapien, vehicula volutpat venenatis ut, blandit nec metus. Maecenas pretium pretium quam, at fermentum erat rhoncus non. In egestas eleifend porta. Sed quis magna metus, eu varius ante. Nam rhoncus sagittis purus, quis suscipit nunc cursus non. Cras adipiscing, ante eu adipiscing faucibus, odio turpis egestas mi, nec semper felis nisl quis justo. Aenean tempus pellentesque metus ut ornare. Sed pellentesque scelerisque nisl eu venenatis. Maecenas tristique est ut nibh pulvinar vitae sagittis ipsum dictum</p>");

            $post->setContent($content);

            $posts[] = $post;
        }
        return $posts;
    }

    /**
     * @param array $posts
     */
    private
    function insertTestPosts($posts)
    {
        foreach ($posts as $post)
        {
            $this->em->persist($post);
            $this->em->flush();
        }
        echo sizeof($posts) . ' posts toegevoegd';
    }

}
